#include "SOFT_SPI.h"
#include "sys/unistd.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

void GPIO_OUTPUT_Init(uint8_t IO)
{
	//zero-initialize the config structure.
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_OUTPUT;
    //bit mask of the pins that you want to set
    io_conf.pin_bit_mask = 1ULL<< IO ;
    //disable pull-down mode
    io_conf.pull_down_en = 0;
    //disable pull-up mode
    io_conf.pull_up_en = 0;
    //configure GPIO with the given settings
    gpio_config(&io_conf);
}

void GPIO_INPUT_Init(uint8_t IO)
{
	//zero-initialize the config structure.
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_INPUT;
    //bit mask of the pins that you want to set
    io_conf.pin_bit_mask = 1ULL<< IO ;
    //disable pull-down mode
    io_conf.pull_down_en = 0;
    //disable pull-up mode
    io_conf.pull_up_en = 0;
    //configure GPIO with the given settings
    gpio_config(&io_conf);
}


void SOFT_SPI_Init(void)
{

    GPIO_OUTPUT_Init(MCP_CS  );
    GPIO_OUTPUT_Init(MCP_MOSI);
    GPIO_OUTPUT_Init(MCP_SCK );

    GPIO_INPUT_Init(MCP_INT );
    GPIO_INPUT_Init(MCP_MISO);

}

void Delay_Ms(uint32_t n)
{
    vTaskDelay(n);
}



/*
* 函数名：u8 mySPI_ReadWriteByte(u8 TxData)
* 输入参数：TxData 待写入的数据
* 返回值：读取到的数据
* 函数作用：模拟SPI读写数据
*/
uint8_t SOFT_SPI_ReadWriteByte(uint8_t TxData)
{
	uint8_t bit_ctr;
	uint8_t result=0xFF;
   	for(bit_ctr=0;bit_ctr<8;bit_ctr++)
   	{
   		result=result<<1;
		if(TxData & 0x80) 
        {
            SOFT_W_MOSI_H();
        }
		else 
        {
            SOFT_W_MOSI_L();
        }
		TxData = (TxData << 1);
		SOFT_W_SCK_H();
		Delay_Ms(2);
		if(SOFT_R_MISO())  
        {
            TxData |= 0x01;
        } 
        Delay_Ms(2);
		SOFT_W_SCK_L();
		Delay_Ms(2);
		if(SOFT_R_MISO())
		{
			result+=1;
		}
		Delay_Ms(2);
   	}
    return(result);
}











